package com.scaffold.commons.datasource;

import java.lang.reflect.Method;

import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.ThrowsAdvice;

public class DataSourceAdvice implements MethodBeforeAdvice, AfterReturningAdvice, ThrowsAdvice {

	// 方法执行之前被调用
	public void before(Method method, Object[] args, Object target)throws Throwable {
		System.out.println("切入点: " + target.getClass().getName() + "类中"	+ method.getName() + "方法");
		
		String methodName = method.getName();
		if (this.isReadMethod(methodName)) {
			DataSourceSwitcher.setDataSource("readOnly");
		} else {
			DataSourceSwitcher.clearDataSource();
		}
	}
	
	private boolean isReadMethod(String methodName){
		return methodName.startsWith("find")
			|| methodName.startsWith("query")
			|| methodName.startsWith("search")
			|| methodName.startsWith("is")
			|| methodName.startsWith("get")
			|| methodName.startsWith("load")
			|| methodName.startsWith("check")
		;
	}
	
	private boolean isWriteMethod(String methodName){
		return methodName.startsWith("add")
			|| methodName.startsWith("create")
			|| methodName.startsWith("save")
			|| methodName.startsWith("edit")
			|| methodName.startsWith("update")
			|| methodName.startsWith("delete")
			|| methodName.startsWith("remove")
		;
	}

	// 方法执行完之后被调用
	public void afterReturning(Object arg0, Method method, Object[] args, Object target) throws Throwable {
		
	}

	// 抛出Exception之后被调用
	public void afterThrowing(Method method, Object[] args, Object target,Exception ex) throws Throwable {
		System.out.println("出现异常");
	}

}

/*
   <!-- 配置aop -->
    <bean id="dataSourceAdvice" class="com.company.aop.DataSourceAdvice" />  
    <aop:config>  
        <aop:advisor pointcut="execution(public * cn.com.company.service..*Service.*(..))" advice-ref="dataSourceAdvice" />  
    </aop:config>
 */
